<template>
  <div class="uploadFile">
    <el-upload
      class="uploadFile-el"
      accept=".jpeg,.jpg,.png"
      :multiple="multiple"
      :limit="limit"
      :show-file-list="false"
      :auto-upload="false"
      :file-list="fileList"
      :on-change="onImageChange"
    >
      <img
        v-if="imageUrl"
        :src="imageUrl"
        class="avatar"
        :style="{ width: preview.width + 'px', height: preview.height + 'px' }"
      />
      <el-icon
        v-else
        class="uploadFile-icon"
        :style="{ width: preview.width - 2 + 'px', height: preview.height - 2 + 'px' }"
        ><Plus
      /></el-icon>
    </el-upload>

    <!-- 图片裁剪组件 -->
    <el-dialog
      class="cropperDialog"
      v-model="cropperVisible"
      title="图片裁剪"
      width="600px"
      append-to-body
    >
      <div class="cropperDialog_content">
        <VueCropper
          ref="cropperRef"
          :img="option.img"
          :outputType="option.outputType"
          :autoCrop="option.autoCrop"
          :fixedNumber="option.fixedNumber"
          :centerBox="option.centerBox"
          :fixed="true"
        />
      </div>
      <div class="cropperDialog_footer">
        <div class="cropperDialog_footer_fun">
          <el-button-group class="ml-4">
            <el-button type="primary" icon="Plus" @click="cropperRef.changeScale(1)" />
            <el-button type="primary" icon="Minus" @click="cropperRef.changeScale(-1)" />
            <el-button type="primary" icon="RefreshLeft" @click="cropperRef.rotateLeft()" />
            <el-button type="primary" icon="RefreshRight" @click="cropperRef.rotateRight()" />
          </el-button-group>
        </div>
        <div class="cropperDialog_footer_btn">
          <el-button type="primary" icon="Check" color="#626aef" circle @click="uploadFile" />
          <el-button type="info" icon="Close" circle @click="cancelUpload" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Upload">
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
import { upload } from "@/api/upload";
const emit = defineEmits(["uploadSuccessCallback"]);
const { proxy } = getCurrentInstance();
const props = defineProps({
  category: { type: String, default: "image" },
  imageUrl: { type: String, default: "" },
  preview: { type: Object, default: { width: 200, height: 200 } },
  cropper: { type: Object, default: { width: 200, height: 200 } },
  multiple: { type: Boolean, default: false },
  limit: { type: Number, default: 1 },
});

const cropperRef = ref();

const fileList = ref([]);
const cropperVisible = ref(false);
const option = reactive({
  img: props.imageUrl || "",
  outputType: "png",
  autoCrop: true,
  centerBox: true,
  fixedNumber: [props.cropper.width, props.cropper.height],
});
const onImageChange = (obj) => {

  if (obj.raw.size <= 1024 * 1024 * 10) {
    const fileReader = new FileReader();

    fileReader.onload = function (e) {
      option.img = e.target.result;
      cropperVisible.value = true;
    };
    fileReader.readAsDataURL(obj.raw);
  } else {
    ElMessage.error("图片大小不能超过10M");
  }

  fileList.value = [];
};

const blobToFile = (blob, fileName) => {
  return new window.File([blob], fileName, { type: blob.type });
};
const uploadFile = () => {
  cropperRef.value.getCropBlob((data) => {
    // do something
    let file = blobToFile(data, "图片." + option.outputType);

    upload({ file, category: props.category }).then((res) => {
      if (res.code == 200) {
        emit("uploadSuccessCallback", res.data.url);
        proxy.$notify({
          title: "上传成功",
          message: "图片上传成功",
          type: "success",
        });
      }
      option.img = "";
      cropperVisible.value = false;
    });
  });
};
const cancelUpload = () => {
  option.img = "";
  cropperVisible.value = false;
};
</script>

<style lang="scss">
.uploadFile {
  .uploadFile-el .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .uploadFile-el .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .uploadFile-el .uploadFile-icon {
    font-size: 50px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
<style lang="scss" scoped>
.cropperDialog {
  &_content {
    height: 40vh;
  }
  &_footer {
    @include flexBox(row, space-between, center);
    padding: 20px 0px 0;
  }
}
</style>
